package com.bawei.main

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.base.BaseActivity
import com.bawei.common.dailog.AppUpdateDialog
import com.bawei.common.event.LiveDataBus
import com.bawei.common.event.LiveDataBusEvent
import com.bawei.jni.NativeLib
import com.bawei.main.adapter.MainPageAdapter
import com.bawei.main.databinding.ActivityMainNavBinding
import com.bawei.main.tab.NormalTabView
import com.bawei.main.tab.RoundTabView
import dagger.hilt.android.AndroidEntryPoint
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener


@Route(path = RoutePath.PATH_MAIN_NAV_PAGE)
@AndroidEntryPoint
class MainActivityNav : BaseActivity<ActivityMainNavBinding>() {

    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPageAdapter: MainPageAdapter
    private lateinit var mNavController: NavigationController

    private var needUserPermissions = arrayListOf(
        Manifest.permission.INTERNET,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.FOREGROUND_SERVICE
    )

    private var unGrantPermissions = arrayListOf<String>()

    private var hasUnGranted = false

    override fun getLayoutId(): Int = R.layout.activity_main_nav

    override fun initViews() {
        //初始化底部导航组件
        mNavController = mDataBinding.mainBottomNav.custom()
            .addItem(newTabItem(R.drawable.nav_home_normal, R.drawable.nav_home_checked, "首页")) //首页
            .addItem(newTabItem(R.drawable.nav_movie_normal, R.drawable.nav_movie_checked, "放映厅")) //放映厅
            .addItem(newRoundTabItem(R.drawable.nav_add_normal, R.drawable.nav_add_checked, "发布")) //发布
            .addItem(newTabItem(R.drawable.nav_live_normal, R.drawable.nav_live_checked, "直播")) //直播
            .addItem(newTabItem(R.drawable.nav_mine_normal, R.drawable.nav_mine_checked, "我的")) //我的
            .build()

        //初始化Fragment数据(推荐)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_HOME).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MOVIE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_LIVE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_MINE).navigation() as Fragment)

        //设置页面数据适配器
        mPageAdapter = MainPageAdapter(supportFragmentManager, fragments, FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT)
        mDataBinding.mainViewPager.adapter = mPageAdapter
        mDataBinding.mainViewPager.offscreenPageLimit = 3 //设置ViewPager前后缓存页面个数

        //设置tab的选中监听事件
        mNavController.addTabItemSelectedListener(object : OnTabItemSelectedListener {
            //选中时触发
            override fun onSelected(index: Int, old: Int) {
                when(index){
                    0, 1 -> mDataBinding.mainViewPager.currentItem = index
                    2 -> {
                        ARouter.getInstance().build(RoutePath.PATH_PUBLISH_PAGE).navigation()
                        mNavController.setSelect(old) //切换之前的Tab
                    }
                    3, 4 -> mDataBinding.mainViewPager.currentItem = index - 1
                }
            }

            //重复点击时触发
            override fun onRepeat(index: Int) {
                Log.i("======", "onRepeat: Index：$index")
                if (index == 2) {
                    ARouter.getInstance().build(RoutePath.PATH_PUBLISH_PAGE).navigation()
                }
            }
        })

        //设置ViewPager页面监听事件
        mDataBinding.mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                Log.i("======", "onPageScrolled: position：$position")
            }

            override fun onPageSelected(position: Int) {
                Log.i("======", "onPageSelected: position：$position")
                when(position){
                    0, 1 ->  mNavController.setSelect(position)
                    2, 3 ->  mNavController.setSelect(position + 1)
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                Log.i("======", "onPageScrollStateChanged: state：$state")
            }
        })

        //订阅LiveDataBus中视频评论事件
        LiveDataBus.with<LiveDataBusEvent>("video_options").observe(this@MainActivityNav){
            handLiveDataBusEvent(it)
        }

        //检查系统权限
        mDataBinding.mainViewPager.postDelayed({
            autoRequestPermission()
        }, 1000)


        Log.i("========", "initViews: ======222===")

        Log.i("========", "initViews: ${NativeLib.stringFromJNI()}")

        Log.i("========", "initViews: ${NativeLib.stringFromJNITwo()}")

    }

    private fun handLiveDataBusEvent(event: LiveDataBusEvent){
        when(event.type){
            100 -> AppUpdateDialog(this@MainActivityNav).show()
            101 -> showToastMsg("视频更多操作！！")
        }
    }

    private fun autoRequestPermission(): Boolean {
        //判断是否是Android6.0，动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //清理历史未授权的权限
            unGrantPermissions.clear()
            //检查用户是否同意过权限
            needUserPermissions.forEach {
                var state = checkSelfPermission(it)
                if (state == PackageManager.PERMISSION_DENIED){
                    unGrantPermissions.add(it)
                }
            }

            //发起用户授权
            if (unGrantPermissions.size > 0){
                requestPermissions(unGrantPermissions.toTypedArray(), 100)
                return false
            }
        }
        return true
    }

    /**
     * 权限检查结果回调
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //检查是否还存在没有授权的权限
        if (requestCode == 100 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            unGrantPermissions.forEach {
                if (checkSelfPermission(it) == PackageManager.PERMISSION_DENIED){
                    hasUnGranted = true
                }
            }
        }
        //给出提示，让用户去设置中手动开启权限
        if (hasUnGranted){
            var builder = AlertDialog.Builder(this@MainActivityNav)
            builder.setTitle("权限提示")
            builder.setMessage("没有授权，请到应用详情中设置")
            builder.setPositiveButton("去设置"){ dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
                openAppDetailPage()
            }
            builder.setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
            }

            //弹窗显示
            //builder.create().show()
        }
    }

    /**
     * 打开应用详情页面
     */
    private fun openAppDetailPage(){
        var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        this@MainActivityNav.startActivity(intent)
    }


    private fun newRoundTabItem(defaultResId: Int, checkedResId: Int, title: String): BaseTabItem{
        var roundTabView = RoundTabView(this@MainActivityNav).apply {
            initData(defaultResId, checkedResId, title)
            setDefaultTextColor(R.color.main_bottom_default_color)
            setCheckedTextColor(R.color.main_bottom_check_color)
        }
        return  roundTabView
    }


    private fun newTabItem(defaultResId: Int, checkedResId: Int, title: String, hasMsg: Boolean = false, msgNum: Int = 0): BaseTabItem{
        var norTabView = NormalTabView(this@MainActivityNav).apply {
            initData(defaultResId, checkedResId, title)
            setDefaultTextColor(R.color.main_bottom_default_color)
            setCheckedTextColor(R.color.main_bottom_check_color)
            if(hasMsg && msgNum > 0){
                setHasMessage(true)
                setMessageNumber(msgNum)
            }
        }
        return  norTabView
    }


}